package com.ease.model.criterion;

import java.util.List;

import com.ease.common.vo.Entry;

/**
 * 
 * @author nathanleewei
 * 
 */
public class SqlCriterion extends CriterionSupport implements Criterion {

	/**
	 *
	 */
	private static final long serialVersionUID = 207126252667924873L;

	private String sql;
	private String[] propertyNames;
	private Object[] propertyValues;

	public SqlCriterion() {

	}

	public String getSql() {
		return sql;
	}

	public void setSql(String sql) {
		this.sql = sql;
	}

	public String[] getPropertyNames() {
		return propertyNames;
	}

	public void setPropertyNames(String[] propertyNames) {
		this.propertyNames = propertyNames;
	}

	public Object[] getPropertyValues() {
		return propertyValues;
	}

	public void setPropertyValues(Object[] propertyValues) {
		this.propertyValues = propertyValues;
	}

	public SqlCriterion(String sql, String[] propertyNames, Object[] propertyValues) {
		this.sql = sql;
		this.propertyNames = propertyNames;
		this.propertyValues = propertyValues;
	}

	public String toSqlString(QueryCriteria queryCriteria) {

		return sql;
	}

	public List<Entry<String, Object>> getNamedValue(QueryCriteria queryCriteria) {

		List<Entry<String, Object>> namedValue = this.safeNamedValue(null);
		if (notEmpty(this.propertyNames)) {
			for (int i = 0; i < propertyNames.length; i++) {
				namedValue.add(new Entry<String, Object>(propertyNames[i], propertyValues[i]));
			}
			// eg sql = ID IN (select id from A where anodeId = ? or znodeId = ?
			// )
			// count the “?" when count > propertyValues
			byte[] temp = sql.getBytes();
			int count = 0;
			for (int i = 0; i < temp.length; i++) {
				if (temp[i] == '?') {
					count++;
				}
			}

			if (count > propertyNames.length && count % propertyNames.length == 0) {
				for (int j = 1; j < count; j++) {
					for (int i = 0; i < propertyNames.length; i++) {
						namedValue.add(new Entry<String, Object>(propertyNames[i], propertyValues[i]));
					}
				}
			}
		}

		return namedValue;
	}

}
